/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sms;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.domain.dto.UserNewPhoneDto;
import com.fzhucc.modules.system.domain.dto.UserPhoneDto;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.utils.RedisUtils;
import com.fzhucc.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description sendRandomCodeSms
 * @date 2023-11-24
 **/
@Service
@RequiredArgsConstructor
public class SmsRegisterRandomCodeService {

    public Random random = new Random();

    @Value("${tencent.sms.expirationTimeStr2}")
    public String expirationTimeStr2;

    @Value("${tencent.sms.expirationTime2}")
    public Long expirationTime2;

    private final SmsService smsService;

    private final RedisUtils redisUtils;

    private final UserSmallRepository userSmallRepository;

    public void sendRegistRandomCode(UserPhoneDto userPhoneDto) {
        //校验手机号是否过期
        //过期 生成随机二维码
        //发送短信
        if (userPhoneDto.getPhone() == null || userPhoneDto.getPhone().equals("")) {
            throw new BadRequestException("验证手机号未找到");
        }
        List<UserSmall> list = userSmallRepository.findAllsByPhone(userPhoneDto.getPhone(), userPhoneDto.getOrgArea());
        if (list != null && list.size() > 0) {
            throw new BadRequestException("请更换手机号,该手机号已注册");
        }
        Object redisResult = redisUtils.get(userPhoneDto.getPhone());
        if (redisResult != null) {
            String code = redisResult.toString();
            //如果存在的话，说明在1分钟内已经发送过验证码了，不能再发了
            if (!StringUtils.isEmpty(code)) {
                throw new BadRequestException("验证码未过期");
            }
        }
        //如果不存在的话,那么redis创建键值对生成验证码并存储，设置过期时间
        String newCode = "";
        // 生成6位随机验证码
        for (int i = 0; i < 6; i++) {
            newCode += random.nextInt(10);
        }
        String phoneArray[] = {userPhoneDto.getPhone()};
        boolean sendResult = smsService.sendtemplatRegistRandomCode(phoneArray, newCode, expirationTimeStr2);
        if (sendResult) {
            //如果发送成功将验证码存储到redis中
            redisUtils.set("reg" + userPhoneDto.getPhone(), newCode, expirationTime2);
        } else {
            throw new BadRequestException("发送失败");
        }
    }

    public void newSendRegistRandomCode(UserNewPhoneDto userPhoneDto) {
        //校验手机号是否过期
        //过期 生成随机二维码
        //发送短信
        if (userPhoneDto.getPhone() == null || userPhoneDto.getPhone().equals("")) {
            throw new BadRequestException("验证手机号未找到");
        }
        List<UserSmall> list = userSmallRepository.findAllsByPhoneWithOutArea(userPhoneDto.getPhone());
        if (list != null && list.size() > 0) {
            throw new BadRequestException("请更换手机号,该手机号已注册");
        }
        Object redisResult = redisUtils.get("regnew" + userPhoneDto.getPhone());
        if (redisResult != null) {
            String code = redisResult.toString();
            //如果存在的话，说明在1分钟内已经发送过验证码了，不能再发了
            if (!StringUtils.isEmpty(code)) {
                throw new BadRequestException("验证码未过期，请输入验证码");
            }
        }
        //如果不存在的话,那么redis创建键值对生成验证码并存储，设置过期时间
        String newCode = "";
        // 生成6位随机验证码
        for (int i = 0; i < 6; i++) {
            newCode += random.nextInt(10);
        }
        String phoneArray[] = {userPhoneDto.getPhone()};
        boolean sendResult = smsService.sendtemplatRegistRandomCode(phoneArray, newCode, expirationTimeStr2);
        if (sendResult) {
            //如果发送成功将验证码存储到redis中
            redisUtils.set("regnew" + userPhoneDto.getPhone(), newCode, expirationTime2);
        } else {
            throw new BadRequestException("发送失败");
        }
    }

    public void sendForgetRandomCode(UserNewPhoneDto userPhoneDto) {
        //校验手机号是否过期
        //过期 生成随机二维码
        //发送短信
        if (userPhoneDto.getPhone() == null || userPhoneDto.getPhone().equals("")) {
            throw new BadRequestException("验证手机号未找到");
        }
        List<UserSmall> list = userSmallRepository.findAllsByPhoneWithOutArea(userPhoneDto.getPhone());
        if (list != null && list.size() > 1) {
            throw new BadRequestException("已存在该手机号多账号的情况，无法修改");
        }
        Object redisResult = redisUtils.get("forget" + userPhoneDto.getPhone());
        if (redisResult != null) {
            String code = redisResult.toString();
            //如果存在的话，说明在1分钟内已经发送过验证码了，不能再发了
            if (!StringUtils.isEmpty(code)) {
                throw new BadRequestException("验证码未过期，请输入验证码");
            }
        }
        //如果不存在的话,那么redis创建键值对生成验证码并存储，设置过期时间
        String newCode = "";
        // 生成6位随机验证码
        for (int i = 0; i < 6; i++) {
            newCode += random.nextInt(10);
        }
        String phoneArray[] = {userPhoneDto.getPhone()};
        //boolean sendResult = smsService.sendtemplatForget(phoneArray, newCode, expirationTimeStr2);
        boolean sendResult = smsService.sendtemplatForget(phoneArray, newCode);
        if (sendResult) {
            //如果发送成功将验证码存储到redis中
            redisUtils.set("forget" + userPhoneDto.getPhone(), newCode, expirationTime2);
        } else {
            throw new BadRequestException("发送失败");
        }
    }
}